package com.toulezu.test.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * 配置数据源和 Mybatis
 * @author chen_k
 *
 */
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {

    @Bean(name = "transactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager() throws Exception {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public DataSource dataSource() throws Exception {
        HikariDataSource dataSource = DataSourceBuilder
                .create()
                //.driverClassName("com.mysql.cj.jdbc.Driver")
                .url("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8")
                .username("root")
                .password("root")
                .type(HikariDataSource.class)
                .build();
        dataSource.setMaximumPoolSize(10);
        dataSource.setAutoCommit(true);
        return dataSource;
    }
}
